package oc.tm.sg.admin.monitor;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import oc.tm.sg.core.monitor.Monitor;
import oc.tm.sg.core.monitor.Statistics;
import oc.tm.sg.core.rpc.annotation.Msg;
import oc.tm.sg.core.rpc.annotation.SPI;

import org.zbus.kit.log.Logger;

/**
 * 监控接收服务端
 * @author lry
 */
@SPI(group="monitor",owner="liry",organization="tm",version="1.0.0")
@Msg(value="监控收集服务器",msg="服务治理数据的监控收集服务器")
public class GovernMonitor implements Monitor {
	
	private static final Logger logger = Logger.getLogger(GovernMonitor.class);

    private volatile boolean running = true;
    private Thread writeThread;
    private BlockingQueue<Statistics> queue;

    public GovernMonitor() {
        queue = new LinkedBlockingQueue<Statistics>(1000);
        writeThread = new Thread(new Runnable() {
            public void run() {
                while (running) {
                    try {
                        writeToDataBase(); // 记录统计日志
                    } catch (Throwable t) { // 防御性容错
                        logger.error("Unexpected error occur at write stat log, cause: " + t.getMessage(), t);
                        try {
                            Thread.sleep(5000); // 失败延迟
                        } catch (Throwable t2) {
                        }
                    }
                }
            }
        });
        writeThread.setDaemon(true);
        writeThread.setName("DubboMonitorAsyncWriteLogThread");
        writeThread.start();
    }

    /**
     * 调用信息数据写入DB
     * @throws Exception
     */
    private void writeToDataBase() throws Exception {
        Statistics statistics = queue.take();
        try {
        	if (logger.isInfoEnabled()) {
        		logger.info("Statistics write to data: "+statistics.toString());
        	}
        } catch (Throwable t) {
            logger.error(t.getMessage(), t);
        }
    }
	

	public void collect(Statistics statistics) {
		queue.offer(statistics);
        if (logger.isInfoEnabled()) {
            logger.info("collect statistics: " + statistics);
        }
	}

	public List<Statistics> lookup(Statistics query) {
		return null;
	}

}
